package haois.security;

import haois.constant.StatusCode;
import haois.constant.daomain.Subject;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * Created by haol on 2017/4/20.
 */
public class ProduceJwt {

    /*
    iss(Issuser)：代表这个JWT的签发主体；
    sub(Subject)：代表这个JWT的主体，即它的所有人；
    aud(Audience)：代表这个JWT的接收对象；
    exp(Expiration time)：是一个时间戳，代表这个JWT的过期时间；
    nbf(Not Before)：是一个时间戳，代表这个JWT生效的开始时间，意味着在这个时间之前验证JWT是会失败的；
    iat(Issued at)：是一个时间戳，代表这个JWT的签发时间；
    jti(JWT ID)：是JWT的唯一标识。
    */
    private HandleToken handleToken = new HandleToken();

    public JwtBuilder createJwtBuilder(String jwtId) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey key = handleToken.generalKey();
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.setHeaderParam("tye", "jwt");
        jwtBuilder.setHeaderParam("alg", "HS256");
        jwtBuilder.setId(jwtId);
        jwtBuilder.setIssuer(StatusCode.JWT_ISSUER);
        jwtBuilder.signWith(signatureAlgorithm, key);//加密
        return jwtBuilder;
    }

    public JwtBuilder produceToken(long jwtTtlMillis) {
        JwtBuilder jwtBuilder = this.createJwtBuilder(StatusCode.JWT_ID);
        if (jwtTtlMillis > 0) {
            long thisTime = System.currentTimeMillis();
            long expMillis = thisTime + jwtTtlMillis;
            Date exp = new Date(expMillis);
            jwtBuilder.setExpiration(exp);
        }
        return jwtBuilder;

    }

    public String produceWebToken(Subject subject, Date issuedTime) {
        String subStr = handleToken.generalSubject(subject);
        return this.produceWebToken(subStr, issuedTime);
    }

    public String produceWebToken(String subStr, Date issuedTime) {
        JwtBuilder jwtBuilder = this.produceToken(StatusCode.JWT_WEB_TTL);
        if (this.isSetIssuedAt()) {
            jwtBuilder.setIssuedAt(issuedTime);//签发时间
        }
        jwtBuilder.setSubject(subStr);//接受主体，此处为登录的用户
        jwtBuilder.setAudience("Web");
        return jwtBuilder.compact();
    }

    public String produceAppToken(Subject subject, Date issuedTime) {
        String subStr = handleToken.generalSubject(subject);
        JwtBuilder jwtBuilder = this.produceToken(StatusCode.JWT_APP_TTL);
        if (this.isSetIssuedAt()) {
            jwtBuilder.setIssuedAt(issuedTime);//签发时间
        }
        jwtBuilder.setSubject(subStr);//接受主体，此处为登录的用户
        jwtBuilder.setAudience("APP");
        return jwtBuilder.compact();
    }

    public boolean isSetIssuedAt() {
        return true;
    }


}
